{% extends "layout.html" %}
{% block content %}
<div class="container">
    <div class="modal fade" id="modal-message" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel"><span id="modal-message-title">Request sent!</span></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <span id="modal-message-content">Request sent! Thank you very much!</span>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
        <div class="col">
            <div><h2 id="service-name"></h1></div>
        </div>
    </div>
    <div class="row">
        <div class="col">
            <div><p id="service-description" class="text-justify"></p></div>
        </div>
    </div>
    <div class="row">
        <div class="col">
            <hr />
            <p>This service is related to the software <a href="{{ url_for('project_bp.get', project_name=service.project.name) }}">{{ service.project.name }}</a>.</p>
            <hr />
        </div>
    </div>
    <div class="row">
        <div class="col">
            <p>Please provide the following information.</p>
        </div>
    </div>
    <div class="row">
        <div class="col">
            <form id="required-informations">
                <div class="form-group">
                    <input type="email" class="form-control" name="email" placeholder="Email" id="form-email" value="" required="true">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" name="firstname" placeholder="Firstname" id="form-firstname" value="" required="true">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" name="lastname" placeholder="Lastname" id="form-lastname" value="" required="true">
                </div>
                <input type="hidden" id="service-id-input" name="service_id" value="">
            </form>
        </div>
    </div>
</div><!-- /.container -->

<script>
$(document).ready(function() {

    var inputTextTemplate = _.template(
        '<input type="<%= input_type %>" class="form-control service-specific" '
        + 'accept="<%= mime_type %>" '
        + 'name="<%= name %>" placeholder="<%= name %>" <%= required %>>');

    var inputFileTemplate = _.template(
        '<input type="<%= input_type %>" class="form-control service-specific" '
        + 'accept="<%= mime_type %>" '
        + 'name="<%= name %>" <%= required %>><%= name %></>');

    var textAreaTemplate = _.template(
        '<textarea class="form-control service-specific" '
        + 'accept="<%= mime_type %>" '
        + 'name="<%= name %>" cols="90" rows="5" <%= required %>><%= name %></textarea>');

    $('#required-informations').on('change', 'input[type=file]', function () {
        var reader = new FileReader();
        var cur_input = $(this);
        reader.onload = (function(theFile) {
            return function(e) {
                cur_input.attr('data', e.target.result);
            };
        })($(this)[0].files[0]);
        reader.readAsDataURL($(this)[0].files[0]);
    });

    // Get information about the service in the URL parameter
    var filters = [{"name": "id", "op": "eq", "val": {{ service.id }}}];
    $.ajax({
        url: "{{ url_for('serviceapi0.serviceapi',) }}",
        data: {"q": JSON.stringify({"filters": filters})},
        dataType: "json",
        contentType: "application/json",
        success: function(data) {
            console.log(data);
            $("#service-name").html(data.objects[0].name);
            $("#service-description").html(data.objects[0].description);
            $("#service-id-input").val(data.objects[0].id);

            data.objects[0].required_informations
            .sort(function (a, b) {
                return a.order - b.order ;
            })
            .map(function (required_information) {

                if (required_information.type == "text") {
                    var cardInput = inputTextTemplate({
                        'input_type': required_information.type,
                        'mime_type': required_information.mimetype,
                        'name': required_information.name,
                        'placeholder': required_information.name,
                        'required': required_information.required ? ' required' : ''
                     });
                } else if (required_information.type == "file")  {
                    var cardInput = inputFileTemplate({
                        'input_type': required_information.type,
                        'mime_type': required_information.mimetype,
                        'name': required_information.name,
                        'placeholder': required_information.name,
                        'required': required_information.required ? ' required' : ''
                     });
                } else if (required_information.type == "textarea")  {
                    var cardInput = textAreaTemplate({
                        'mime_type': required_information.mimetype,
                        'name': required_information.name,
                        'required': required_information.required ? ' required' : '',
                        'name': required_information.name
                    });
                }

                $('#required-informations')
                .append('<div class="form-group">'+ cardInput + '</div>');
            });
            $('#required-informations')
            .append('<button type="submit" value="OK" class="btn btn-primary">OK</button>');
        }
    });
});


$("#required-informations").submit(function(event) {
    event.preventDefault();

    var requests_informations = {};
    var service_required_informations = {};
    $('form#required-informations :input').each(function() {
        if (! $(this).is( ":button" )) {
            if ($(this).hasClass('service-specific')) {
                if ($(this).attr('type') == 'file') {
                    service_required_informations[$(this).attr('name')] = $(this).attr('data');
                } else {
                    service_required_informations[$(this).attr('name')] = $(this).val();
                }
            } else {
                requests_informations[$(this).attr('name')] = $(this).val();
            }
        }
    });

    requests_informations['required_informations'] = service_required_informations;

    $.ajax({
        url: "{{ url_for('requestapi0.requestapi') }}",
        type: 'POST',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(requests_informations),
        headers: {
            contentType: "application/json"
        },
        success: function(result) {
            $('#required-informations').trigger("reset");
            $("#modal-message-title").html('Success');
            $("#modal-message-content").html('Request sent! Thank you very much!');
            $('#modal-message').modal('show');
        },
        error: function(error) {
            $("#modal-message-title").html('Error');
            $("#modal-message-content").html($.parseJSON(error.responseText).message);
            $('#modal-message').modal('show');
        }
    });
});
</script>
{% endblock %}
